package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.constant.CacheConstants;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 菜品业务实现
 *
 * @Author itcast
 * @Create 2023/3/7
 **/
@Service
@Slf4j
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    /**
     * 添加菜品
     *
     * @param dishDTO
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addDish(DishDTO dishDTO) {
        Dish dish=new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        this.save(dish);
        if (!dishDTO.getFlavors().isEmpty()) {
            dishDTO.getFlavors().stream().forEach(x->{
                DishFlavor dishFlavor=new DishFlavor();
                BeanUtils.copyProperties(x, dishFlavor);
                dishFlavor.setDishId(dish.getId());
                dishFlavorMapper.insert(dishFlavor);
            });
        }
        deleteCache(dish.getCategoryId());

    }

    /**
     * 菜品分页条件查询
     *
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult dishPageList(DishPageQueryDTO dishPageQueryDTO) {

        Page<Dish> page = new Page<>(dishPageQueryDTO.getPage(),dishPageQueryDTO.getPageSize());
        this.lambdaQuery()
                .eq(dishPageQueryDTO.getCategoryId()!=null, Dish::getCategoryId,dishPageQueryDTO.getCategoryId())
                .like(StringUtils.hasLength(dishPageQueryDTO.getName()), Dish::getName,dishPageQueryDTO.getName())
                .eq(dishPageQueryDTO.getStatus()!=null, Dish::getStatus,dishPageQueryDTO.getStatus())
                .page(page);

        return new PageResult(page.getTotal(),page.getRecords());
    }

    /**
     * 删除菜品
     *
     * @param ids
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteDish(List<Integer> ids) {
        List<Dish> dishList = this.listByIds(ids);
        dishList.stream()
                .map(Dish::getCategoryId)
                .distinct()//去重
                .forEach(this::deleteCache);

        this.remove(Wrappers.<Dish>lambdaQuery().in(Dish::getId,ids));


    }

    /**
     * 根据id查询菜品
     *
     * @param id
     * @return
     */
    @Override
    public DishVO findById(Integer id) {
        Dish dish = this.getById(id);
        List<DishFlavor> dishFlavors = dishFlavorMapper.selectList(Wrappers.<DishFlavor>lambdaQuery().eq(DishFlavor::getDishId, id));
        DishVO dishVO=new DishVO();
        if (dish!=null) {
            BeanUtils.copyProperties(dish,dishVO);
            dishVO.setFlavors(dishFlavors);
        }
        return dishVO;
    }

    /**
     * 修改菜品
     *
     * @param dishDTO
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateDish(DishDTO dishDTO) {

        if (dishDTO!=null) {
            Dish dish=new Dish();
            BeanUtils.copyProperties(dishDTO,dish);
            dish.setCreateTime(LocalDateTime.now());
            dish.setUpdateTime(LocalDateTime.now());
            this.updateById(dish);
            if (!dishDTO.getFlavors().isEmpty()) {
                dishDTO.getFlavors().stream().forEach(x->{
                    DishFlavor dishFlavor=new DishFlavor();
                    BeanUtils.copyProperties(x, dishFlavor);
                    dishFlavor.setDishId(dish.getId());
                    dishFlavorMapper.insert(dishFlavor);
                });
            }
        }else {
            throw new RuntimeException("参数异常");
        }
        deleteCache(this.getById(dishDTO.getId()).getCategoryId());
    }

    /**
     * 修改菜品状态
     *
     * @param status
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateDishStatus(Integer status, Long id) {
        Dish dish = Dish.builder().id(id).status(status).build();
        this.updateById(dish);
        deleteCache(this.getById(id).getCategoryId());
    }
    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    /**
     * 根据分类查询菜品
     *
     * @param categoryId
     * @return
     */
    @Override
    public List<DishVO> findByCategoryId(Long categoryId) {
        String dishVOListJson = (String) stringRedisTemplate.opsForHash().get(CacheConstants.DISH_CATEGORY_ID, categoryId.toString());

        if (!StringUtils.hasLength(dishVOListJson)) {
            List<Dish> list = this.lambdaQuery().eq(Dish::getCategoryId, categoryId).eq(Dish::getStatus,1).list();
            List<DishVO> dishVOList = list.stream().map(x -> {
                List<DishFlavor> dishFlavors = dishFlavorMapper.selectList(Wrappers.<DishFlavor>lambdaQuery().eq(DishFlavor::getDishId, x.getId()));
                DishVO dishVO = new DishVO();
                BeanUtils.copyProperties(x, dishVO);
                dishVO.setFlavors(dishFlavors);
                return dishVO;
            }).collect(Collectors.toList());
            stringRedisTemplate.opsForHash().put(CacheConstants.DISH_CATEGORY_ID, categoryId.toString(), JSON.toJSONString(dishVOList));
            return dishVOList;
        }

        List<DishVO> dishVOList = JSON.parseArray(dishVOListJson, DishVO.class);
        return dishVOList;
    }

    /**
     * 删除缓存
     * @param categoryId
     */
    public void deleteCache(Long categoryId){
        stringRedisTemplate.opsForHash().delete(CacheConstants.DISH_CATEGORY_ID, categoryId.toString());
    }
}
